<template>
  <div class="political-container">
    <el-card class="main-card">
      <div slot="header" class="header">
        <div class="title-area">
          <h3>思政表现评分</h3>
          <el-tag type="info" effect="plain">导师专用功能</el-tag>
        </div>
        <div class="term-selector">
          <el-select v-model="queryParams.year" placeholder="选择年份" size="small">
            <el-option
              v-for="year in yearOptions"
              :key="year"
              :label="year + '年'"
              :value="year">
            </el-option>
          </el-select>
          <el-select v-model="queryParams.semester" placeholder="选择学期" size="small" style="margin-left: 10px;">
            <el-option label="春季" value="春季"></el-option>
            <el-option label="秋季" value="秋季"></el-option>
          </el-select>
          <el-button type="primary" size="small" @click="handleQuery" style="margin-left: 10px;" icon="el-icon-search">查询</el-button>
        </div>
      </div>

      <!-- 搜索区域 -->
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item>
          <el-input v-model="queryParams.keyword" placeholder="请输入学号/姓名" clearable>
            <el-button slot="append" icon="el-icon-search" @click="handleQuery"></el-button>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetQuery" plain icon="el-icon-refresh">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格区域 -->
      <el-table :data="studentList" border stripe style="width: 100%" v-loading="loading" 
                :header-cell-style="{'background-color': '#f5f7fa', 'color': '#606266'}"
                :row-class-name="tableRowClassName">
        <el-table-column prop="student_no" label="学号" width="120" align="center"></el-table-column>
        <el-table-column prop="name" label="姓名" width="100" align="center"></el-table-column>
        <el-table-column prop="college" label="学院" align="center"></el-table-column>
        <el-table-column prop="major" label="专业" align="center"></el-table-column>
        <el-table-column prop="grade" label="年级" width="80" align="center"></el-table-column>
        <el-table-column prop="class_name" label="班级" width="100" align="center"></el-table-column>
        <el-table-column label="思政评分" width="280" align="center">
          <template slot-scope="scope">
            <div class="score-display-row">
              <el-tag type="info" size="mini">基:{{ scope.row.base_score || 0 }}</el-tag>
              <el-tag type="success" size="mini">荣:{{ scope.row.honor_score || 0 }}</el-tag>
              <el-tag type="primary" size="mini">师:{{ scope.row.advisor_score || '未评' }}</el-tag>
              <el-tag type="danger" size="mini">总:{{ scope.row.total_score || 0 }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button-group>
              <el-tooltip content="评分" placement="top">
                <el-button type="primary" size="mini" @click="handleScore(scope.row)" icon="el-icon-edit"></el-button>
              </el-tooltip>
              <el-tooltip content="详情" placement="top">
                <el-button type="info" size="mini" @click="handleDetail(scope.row)" icon="el-icon-view"></el-button>
              </el-tooltip>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 空数据提示 -->
      <div v-if="studentList.length === 0 && !loading" class="empty-block">
        <el-empty description="暂无学生数据"></el-empty>
      </div>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.pageNum"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="queryParams.pageSize"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 评分对话框 -->
    <el-dialog :title="'思政表现评分 - ' + scoreForm.studentName" :visible.sync="scoreDialogVisible" width="50%" :close-on-click-modal="false">
      <el-card shadow="never" class="info-card">
        <div class="student-info">
          <div class="info-item"><span class="label">学号：</span>{{ scoreForm.studentNo }}</div>
          <div class="info-item"><span class="label">姓名：</span>{{ scoreForm.studentName }}</div>
          <div class="info-item"><span class="label">班级：</span>{{ scoreForm.className }}</div>
        </div>
      </el-card>
      
      <el-form :model="scoreForm" :rules="rules" ref="scoreForm" label-width="100px" class="score-form">
        <el-form-item label="基础分" prop="baseScore">
          <el-input-number v-model="scoreForm.baseScore" :min="0" :max="100" :step="1" controls-position="right"></el-input-number>
          <span class="score-hint">（基础分由系统根据学生日常表现自动计算）</span>
        </el-form-item>
        <el-form-item label="荣誉分" prop="honorScore">
          <el-input-number v-model="scoreForm.honorScore" :min="0" :max="100" :step="1" controls-position="right"></el-input-number>
          <span class="score-hint">（荣誉分由系统根据学生获得的荣誉自动计算）</span>
        </el-form-item>
        <el-form-item label="导师评分" prop="advisorScore">
          <el-input-number v-model="scoreForm.advisorScore" :min="0" :max="100" :step="1" controls-position="right"></el-input-number>
          <span class="score-hint">（导师根据学生思想政治表现进行评分）</span>
        </el-form-item>
        <el-form-item label="导师评语" prop="advisorComment">
          <el-input type="textarea" v-model="scoreForm.advisorComment" :rows="4" placeholder="请输入评语"></el-input>
        </el-form-item>
        <el-form-item label="总分">
          <div class="total-score-display">
            <span class="total-score">{{ calculateTotalScore() }}</span>
            <span class="score-hint">（总分 = 基础分 + 荣誉分 + 导师评分）</span>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="scoreDialogVisible = false" icon="el-icon-close">取 消</el-button>
        <el-button type="primary" @click="submitScore" :loading="submitLoading" icon="el-icon-check">提 交</el-button>
      </div>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog title="思政表现详情" :visible.sync="detailDialogVisible" width="60%">
      <template v-if="detailData">
        <el-card shadow="never" class="detail-card">
          <div slot="header">
            <span>学生基本信息</span>
          </div>
          <el-descriptions :column="3" border>
            <el-descriptions-item label="学号">{{ detailData.studentInfo?.student_id }}</el-descriptions-item>
            <el-descriptions-item label="姓名">{{ detailData.studentInfo?.name }}</el-descriptions-item>
            <el-descriptions-item label="学院">{{ detailData.studentInfo?.college }}</el-descriptions-item>
            <el-descriptions-item label="专业">{{ detailData.studentInfo?.major }}</el-descriptions-item>
            <el-descriptions-item label="年级">{{ detailData.studentInfo?.grade }}</el-descriptions-item>
            <el-descriptions-item label="班级">{{ detailData.studentInfo?.class_name }}</el-descriptions-item>
          </el-descriptions>
        </el-card>

        <el-card shadow="never" class="detail-card">
          <div slot="header">
            <span>思政评分</span>
          </div>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="基础分">
              <el-tag size="medium">{{ detailData.politicalInfo?.base_score || 0 }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="荣誉分">
              <el-tag size="medium" type="success">{{ detailData.politicalInfo?.honor_score || 0 }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="导师评分">
              <el-tag size="medium" type="primary">{{ detailData.politicalInfo?.advisor_score || '未评' }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="总分">
              <el-tag size="medium" type="danger">{{ detailData.politicalInfo?.total_score || 0 }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="导师评语" :span="2">
              <div class="comment-box">
                {{ detailData.politicalInfo?.advisor_comment || '暂无评语' }}
              </div>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </template>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false" icon="el-icon-close">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'Political',
  data() {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: '',
        year: null,
        semester: null
      },
      // 年份选项
      yearOptions: [],
      // 学生列表
      studentList: [],
      // 总记录数
      total: 0,
      // 加载状态
      loading: false,
      // 提交加载状态
      submitLoading: false,
      // 评分对话框可见性
      scoreDialogVisible: false,
      // 详情对话框可见性
      detailDialogVisible: false,
      // 评分表单
      scoreForm: {
        studentId: null,
        studentNo: '',
        studentName: '',
        className: '',
        baseScore: 0,
        honorScore: 0,
        advisorScore: null,
        advisorComment: '',
        year: null,
        semester: null
      },
      // 详情数据
      detailData: null,
      // 表单验证规则
      rules: {
        advisorScore: [
          { required: true, message: '请输入导师评分', trigger: 'blur' },
          { type: 'number', min: 0, max: 100, message: '分数范围为0-100', trigger: 'blur' }
        ],
        advisorComment: [
          { required: true, message: '请输入导师评语', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.initYearOptions()
    this.getCurrentTerm()
  },
  methods: {
    // 初始化年份选项
    initYearOptions() {
      const currentYear = new Date().getFullYear()
      this.yearOptions = []
      for (let i = 0; i < 5; i++) {
        this.yearOptions.push(currentYear - i)
      }
    },
    
    // 获取当前学期
    getCurrentTerm() {
      request.get('/score/political/current-term').then(res => {
        if (res.code === 200) {
          this.queryParams.year = res.data.year
          this.queryParams.semester = res.data.semester
          this.getStudentList()
        }
      }).catch(err => {
        console.error('获取当前学期失败:', err)
        // 默认使用当前年份
        this.queryParams.year = new Date().getFullYear()
        // 根据月份判断学期
        const month = new Date().getMonth() + 1
        this.queryParams.semester = month >= 2 && month <= 7 ? '春季' : '秋季'
        this.getStudentList()
      })
    },
    
    // 获取学生列表
    getStudentList() {
      // 获取当前登录用户ID
      const userInfoStr = window.sessionStorage.getItem('userInfo')
      if (!userInfoStr) {
        this.$message.error('请先登录')
        this.$router.push('/login')
        return
      }
      
      const userInfo = JSON.parse(userInfoStr)
      if (!userInfo || !userInfo.id) {
        this.$message.error('用户信息不完整，请重新登录')
        this.$router.push('/login')
        return
      }
      
      // 显示加载状态
      this.loading = true
      
      // 获取当前导师ID下的学生思政评分
      request.get('/score/political/list', {
        params: {
          advisorId: userInfo.id,
          keyword: this.queryParams.keyword,
          year: this.queryParams.year,
          semester: this.queryParams.semester
        }
      }).then(res => {
        this.loading = false
        if (res.code === 200) {
          this.studentList = res.data || []
          this.total = this.studentList.length
        } else {
          this.$message.error(res.msg || '获取学生列表失败')
        }
      }).catch(err => {
        this.loading = false
        console.error('获取学生列表错误:', err)
        this.$message.error('获取学生列表失败，请稍后重试')
      })
    },
    
    // 处理查询
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getStudentList()
    },
    
    // 重置查询
    resetQuery() {
      this.queryParams.keyword = ''
      this.handleQuery()
    },
    
    // 处理分页大小变化
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getStudentList()
    },
    
    // 处理页码变化
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.getStudentList()
    },
    
    // 表格行样式
    tableRowClassName({row, rowIndex}) {
      if (!row.advisor_score) {
        return 'warning-row'
      }
      return ''
    },
    
    // 处理评分
    handleScore(row) {
      if (this.detailDialogVisible) {
        this.detailDialogVisible = false
      }
      
      this.scoreForm = {
        studentId: row.student_id || row.id,
        studentNo: row.student_no || row.student_id,
        studentName: row.name,
        className: row.class_name || row.grade,
        baseScore: row.base_score || 0,
        honorScore: row.honor_score || 0,
        advisorScore: row.advisor_score || null,
        advisorComment: '',
        year: this.queryParams.year,
        semester: this.queryParams.semester
      }
      
      // 获取详细信息
      request.get('/score/political/detail', {
        params: {
          studentId: row.student_id || row.id,
          year: this.queryParams.year,
          semester: this.queryParams.semester
        }
      }).then(res => {
        if (res.code === 200 && res.data.politicalInfo) {
          const politicalInfo = res.data.politicalInfo
          this.scoreForm.baseScore = politicalInfo.base_score || 0
          this.scoreForm.honorScore = politicalInfo.honor_score || 0
          this.scoreForm.advisorScore = politicalInfo.advisor_score
          this.scoreForm.advisorComment = politicalInfo.advisor_comment || ''
        }
        this.scoreDialogVisible = true
      }).catch(err => {
        console.error('获取思政评分详情失败:', err)
        this.$message.error('获取思政评分详情失败，请稍后重试')
      })
    },
    
    // 处理详情
    handleDetail(row) {
      request.get('/score/political/detail', {
        params: {
          studentId: row.student_id,
          year: this.queryParams.year,
          semester: this.queryParams.semester
        }
      }).then(res => {
        if (res.code === 200) {
          this.detailData = res.data
          this.detailDialogVisible = true
        } else {
          this.$message.error(res.msg || '获取详情失败')
        }
      }).catch(err => {
        console.error('获取详情错误:', err)
        this.$message.error('获取详情失败，请稍后重试')
      })
    },
    
    // 计算总分
    calculateTotalScore() {
      let total = 0
      if (this.scoreForm.baseScore) total += parseFloat(this.scoreForm.baseScore)
      if (this.scoreForm.honorScore) total += parseFloat(this.scoreForm.honorScore)
      if (this.scoreForm.advisorScore) total += parseFloat(this.scoreForm.advisorScore)
      return total.toFixed(2)
    },
    
    // 提交评分
    submitScore() {
      this.$refs.scoreForm.validate(valid => {
        if (valid) {
          this.submitLoading = true
          // 确保所有数值都是有效的数字
          const baseScore = parseFloat(this.scoreForm.baseScore || 0).toFixed(2);
          const honorScore = parseFloat(this.scoreForm.honorScore || 0).toFixed(2);
          const advisorScore = parseFloat(this.scoreForm.advisorScore || 0).toFixed(2);
          
          request.post('/score/political/save', {
            studentId: this.scoreForm.studentId,
            baseScore: baseScore,
            honorScore: honorScore,
            advisorScore: advisorScore,
            advisorComment: this.scoreForm.advisorComment || '',
            year: this.queryParams.year,
            semester: this.queryParams.semester
          }).then(res => {
            this.submitLoading = false
            if (res.code === 200) {
              this.$message.success('评分保存成功')
              this.scoreDialogVisible = false
              this.getStudentList()
            } else {
              this.$message.error(res.msg || '保存失败')
            }
          }).catch(err => {
            this.submitLoading = false
            console.error('保存评分错误:', err)
            this.$message.error('保存评分失败: ' + (err.message || '未知错误'))
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
.political-container {
  padding: 20px;
}

.main-card {
  margin-bottom: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-area {
  display: flex;
  align-items: center;
}

.title-area h3 {
  margin: 0;
  margin-right: 10px;
}

.search-form {
  margin-bottom: 20px;
}

.score-display {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  justify-content: center;
}

.score-display-row {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  gap: 2px;
  justify-content: space-between;
  width: 100%;
}

.score-display-row .el-tag {
  padding: 0 4px;
  font-size: 11px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.score-hint {
  margin-left: 10px;
  color: #909399;
  font-size: 12px;
}

.total-score {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
}

.empty-data {
  text-align: center;
  color: #909399;
  padding: 20px 0;
}

.info-card {
  margin-bottom: 20px;
}

.student-info {
  display: flex;
  flex-wrap: wrap;
}

.info-item {
  margin-right: 20px;
  margin-bottom: 10px;
}

.label {
  font-weight: bold;
  color: #606266;
}

.score-form {
  margin-top: 20px;
}

.detail-card {
  margin-bottom: 20px;
}

.comment-box {
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
  min-height: 60px;
}

.empty-block {
  margin: 30px 0;
}

.total-score-display {
  display: flex;
  align-items: center;
}

/* 未评分行的样式 */
.el-table .warning-row {
  background-color: #fdf6ec;
}

/* 按钮组样式优化 */
.el-button-group {
  display: flex;
  justify-content: center;
}

.el-button-group .el-button {
  padding: 7px 10px;
}

.el-button-group .el-button+.el-button {
  margin-left: -1px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding-top: 10px;
}

.dialog-footer .el-button {
  margin-left: 10px;
}
</style> 